<script setup>
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import { useUserStore } from '@/stores/userStore'
import { useLogSocketStore } from '@/stores/LogSocketStore.js'

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({}),
  },
})

const router = useRouter()

const rail = ref(false)

const avatar = computed(() =>
  props.userInfo.avatar == null ? defaultAvatar : props.userInfo.avatar,
)

const defaultAvatar = 'https://cdn.vuetifyjs.com/images/john.jpg'

// 不同角色的菜单项
let menuMap = {
  ROLE_ADMIN: [
    { title: '首页', icon: 'mdi-home', route: '/index' },
    { title: '文档管理', icon: 'mdi-folder', route: '/files' },
    { title: '用户管理', icon: 'mdi-account-group', route: '/users' },
    { title: '标签管理', icon: 'mdi-tag', route: '/tags' },
    { title: '角色管理', icon: 'mdi-shield-account', route: '/roles' },
    { title: '日志管理', icon: 'mdi-file-document', route: '/logs' },
    { title: '回收站', icon: 'mdi-delete', route: '/recycle-bin' },
  ],
}

// 动态计算当前用户菜单
const menus = computed(() => {
  return props.userInfo.roles
    .map((role) => menuMap[role])
    .filter(Boolean) // 过滤 undefined
    .flat()
})

const goTo = (route) => {
  router.push(route)
}

const logout = () => {
  // 清理登录状态（如 token、用户信息）
  useUserStore().logout()
  localStorage.removeItem('token')
  useLogSocketStore().disconnect()
  // 这里简单跳转
  router.push('/login')
}

const drawer = ref(true)
const group = ref(null)

watch(group, () => {
  drawer.value = false
})
</script>

<template>
  <v-app-bar :elevation="2">
    <v-app-bar-nav-icon variant="text" @click.stop="rail = !rail"></v-app-bar-nav-icon>

    <v-toolbar-title>QAQ</v-toolbar-title>

    <v-spacer></v-spacer>

    <!-- 用户头像（不触发菜单） -->
    <v-avatar size="48">
      <v-img :src="avatar" alt="User" />
    </v-avatar>

    <!-- 用户名菜单 -->
    <v-menu offset-y>
      <template #activator="{ props }">
        <v-btn v-bind="props" variant="text" class="ml-2 text-none">
          你好，{{ userInfo.username }}
        </v-btn>
      </template>

      <v-list>
        <v-list-item @click="goTo('/me')">
          <v-list-item-title>个人中心</v-list-item-title>
        </v-list-item>
        <v-list-item @click="logout">
          <v-list-item-title>退出登录</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </v-app-bar>

  <v-navigation-drawer class="bg-blue-lighten-4" v-model="drawer" :rail="rail" permanent>
    <v-list :lines="false" density="compact" nav>
      <v-list-item
        v-for="(menu, i) in menus"
        :key="i"
        :value="menu"
        color="primary"
        @click="goTo(menu.route)"
      >
        <template v-slot:prepend>
          <v-icon :icon="menu.icon"></v-icon>
        </template>

        <v-list-item-title>{{ menu.title }}</v-list-item-title>
      </v-list-item>
    </v-list>
  </v-navigation-drawer>
</template>
